# -*- coding:utf-8 -*-
import os
import time

from PIL import Image
from mss import mss
from ..report.__remote_log__ import RemoteLogger
from ..report.log import logger
from ..common.__const__ import LOG_PATH
from ..common.__script_config__ import script_config
from ..webdriver.reuse_remote import ReuseRemote
from .. import webdriver
from hslib import webdriver as HSWebDriver
from qturboframe.lib.utils.thread_local import main_thread_local


class Picture(object):
    '''
    获取界面图片

    :Attributes:
     - flag: 使用截图的类型，包括appui、webui、csui三种
     - url: 发送图片到日志服务器的url地址
    '''

    def __init__(self,flag):
        self.flag = flag
        self.url = script_config.remote_log_url

    def get_picture(self, driver:webdriver.HSWebDriver=None):
        '''
        界面截图方法，同时保存图片

        :Args:
         - driver: 用于webui截图，appui、csui截图不需要

        :Returns:
            返回图片地址

        :Example:
         - 例1: path = Picture('webui').get_picture(driver)
         - 例2: path = Picture('csui').get_picture()
         - 例3: path = Picture('appui').get_picture()
        '''
        if self.flag.lower() == 'webui':
            if (driver.__class__ == webdriver.HSChrome or driver.__class__ == webdriver.HSFirefox
                    or driver.__class__ == webdriver.HSIe or driver.__class__ == ReuseRemote
            or driver.__class__ == HSWebDriver.HSChrome or driver.__class__ == HSWebDriver.HSFirefox
                    or driver.__class__ == HSWebDriver.HSIe):
                picture_path = driver.get_windows_img(self.__get_img_path())
            else:
                raise AttributeError('driver参数为非HSWebDriver类！')
        elif self.flag.lower() == 'csui':
            picture_path = self.__get_screen_pic()
        elif self.flag.lower() == 'appui':
            picture_path = self.__get_app_screen_pic()
        else:
            raise AttributeError('Picture类flag参数异常！')
        if picture_path:
            url = RemoteLogger().send_picture(picture_path)
            # 插入图片处打上标记
            logger.info('此处截图，图片访问地址：{0}'.format(url))
            return url

    def __get_screen_pic(self):
        '''桌面截屏'''
        img_name = self.__get_img_path()
        screen_name = os.path.join(LOG_PATH, img_name)
        # 如果日志目录不存在，则创建目录
        if not os.path.exists(LOG_PATH):
            os.makedirs(LOG_PATH)
        try:
            # im = ImageGrab.grab()
            # im.save(screen_name)
            self.__get_screenshot(screen_name)
            logger.info("Had take screenshot '" + img_name + "' and save to folder : " + LOG_PATH)
        except:
            logger.debug("not take screenshot! ignore!!!")
        return screen_name

    def __get_screenshot(self, screen_name):
        with mss() as m:
            rect = m.monitors[0]
            img = m.grab(rect)

            pim = Image.new("RGB", img.size)
            pim.frombytes(img.rgb)
            pim.save(screen_name, quality=95)

            del img, pim

    def __get_app_screen_pic(self):
        '''手机截屏'''
        try:
            from airtest.core.api import snapshot
        except Exception as msg:
            logger.warn(str(msg))
            return
        if LOG_PATH:
            img_name = self.__get_img_path()
            screen_name = LOG_PATH + img_name
            # 如果日志目录不存在，则创建目录
            if not os.path.exists(LOG_PATH):
                os.makedirs(LOG_PATH)
            try:
                snapshot(screen_name)
                logger.info("Had take screenshot '" + img_name + "' and save to folder : " + LOG_PATH)
            except:
                logger.debug("not take screenshot! ignore!!!")
        else:
            screen_name = None
        return screen_name

    def __get_img_path(self):
        '''
        创建图片路径

        :Returns:
            返回图片路径的字符串
        '''
        try:
            img_path = time.strftime(main_thread_local.case_id.replace("|", "_") + '_%Y%m%d%H%M%S',
                                     time.localtime(time.time())) + '.png'
        except Exception as e:
            img_path = time.strftime('%Y%m%d%H%M%S',
                                     time.localtime(time.time())) + '.png'
        return img_path
